package com.au.bescene.activity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.au.bescene.R;
import com.au.bescene.adapter.PhotoGalleryListAdapter;
import com.au.bescene.entity.Event;
import com.au.bescene.util.Util;

/**
 * Represents the list of Photo Galleries.
 * @author Khaled
 *
 */
public class PhotoGalleryList extends ListActivity {
	private ArrayList<Event> _events = new ArrayList<Event>();
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.photogallerylist);

		initializePhotoGalleryList();

	}
	
	/**
	 * Initializes the list of Photo Galleries.
	 */
	private void initializePhotoGalleryList() {
		getListOfGalleriesFromServer();

		if(_events.size() > 0) {
			PhotoGalleryListAdapter adapter = new PhotoGalleryListAdapter(this, _events);
			setListAdapter(adapter);
		}
		else {
			Toast.makeText(getApplicationContext(), getResources().getString(R.string.photogallerylist_nogalleries), Toast.LENGTH_SHORT).show();
			this.finish();
		}		
	}

	/**
	 * Listens to click events for PhotoGalleryList items.
	 */
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		if(isOnline()) {
			Intent intent = new Intent(PhotoGalleryList.this, PhotoGallery.class);
			intent.putExtra("foldername", _events.get(position).getFolderName());
			startActivity(intent);
		}
		else {
			Toast.makeText(getApplicationContext(), getResources().getString(R.string.internetrequired), Toast.LENGTH_SHORT).show();
		}	
	}
	
	/**
	 * Gets the list of photo galleries from BeScene server.
	 */
	private void getListOfGalleriesFromServer() {
		String result = "";
		
		try {
			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(getResources().getString(R.string.photogallerylist_script)); 
		    HttpResponse response = httpclient.execute(httppost);
		    HttpEntity entity = response.getEntity();
		    InputStream is = entity.getContent();

			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
		    StringBuilder sb = new StringBuilder();
		    String line = null;
		    
		    while ((line = reader.readLine()) != null) {
		    	sb.append(line + "\n");
		    }
		    
		    is.close();
		    result=sb.toString();
		} catch(Exception e) {
			Log.e("log_tag" , "Error converting result "+e.toString());
		}
	 
		try {
			JSONArray jArray = new JSONArray(result);
			
			
			for(int i = 2; i<jArray.length(); i++) {
				result="";
				result = jArray.getString(i);
				
				Event event = Util.parseNameToEvent(result);
				_events.add(event);
			}

		} catch(JSONException e) {
			Log.e("log_tag", "Error parsing data "+e.toString());
		}
	}	
	
	/**
	 * Checks if mobile phone is connected to the internet.
	 * @return network status.
	 */
	private boolean isOnline() {
	    ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo netInfo = cm.getActiveNetworkInfo();
	    if (netInfo != null && netInfo.isConnected()) {
	        return true;
	    }
	    return false;
	}
}
